/*
 * @(#)Xml2MapInterceptor.java $version 2010. 8. 11
 *
 * Copyright 2007-2010 NHN Corp. All rights Reserved. 
 * NHN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.nhncorp.usf.core.interceptor.impl;

import java.io.InputStream;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.nhncorp.lucy.common.util.ConvertUtil;
import com.nhncorp.lucy.web.interceptor.AbstractInterceptor;

import com.nhncorp.usf.core.util.StringUtil;
import com.nhncorp.usf.core.xwork.ActionInvocationHelper;

import com.opensymphony.xwork.ActionInvocation;

/**
 * {@link UsfInterceptor} to convert xml of paremter to {@link Map}.
 * {@link ApplicationInfo#getNativeEncoding(String)} must be not null.
 * Before converted data is inserted into {@link Map}, prefix part of parameterName is removed.
 * If prefix is "xml_" and parameterName is "xml_sample", key of {@link Map} which references converted data
 * is "sample".
 *
 * @author Web Platform Development Team
 */
@SuppressWarnings("serial")
public class Xml2MapInterceptor extends AbstractInterceptor {
    Log log = LogFactory.getLog(Xml2MapInterceptor.class);

    /**
     * prefix of parameter-name which has xml-type value.
     */
    private String prefixOfParamter = "xml_";

    /**
     * Sets the prefix of paramter.
     *
     * @param prefixOfParamter the new prefix of paramter
     */
    public void setPrefixOfParamter(String prefixOfParamter) {
        this.prefixOfParamter = prefixOfParamter;
    }

    /**
     * replace xml to converted {@link Map}.
     *
     * @param actionInvocation the ActionInvocation
     * @return the interceptor result
     * @throws Exception for Exception
     */
    public String intercept(ActionInvocation actionInvocation) throws Exception {
        Map<String, Object> dataMap = ActionInvocationHelper.getDataMap(actionInvocation);

        for (Entry<String, Object> entry : dataMap.entrySet()) {
            String parameterName = entry.getKey();

            if (!parameterName.startsWith(prefixOfParamter)) {
                continue;
            }

            String xmlString = (String)entry.getValue();
            try {
                InputStream inputStream = ConvertUtil.stringToInputStream(xmlString);
                Map<String, Object> convertedMap = ConvertUtil.xml2map(inputStream);
                dataMap.put(StringUtil.substringAfter(parameterName, prefixOfParamter), convertedMap);

                if (log.isDebugEnabled()) {
                    log.debug("xml(" + xmlString + ") is convertd to Map(" + convertedMap + ").");
                }
            } catch (Exception except) {
                log.error("xml(" + xmlString + ") is not convertd to Map.", except);
            }

        }

        return actionInvocation.invoke();
    }
}